package chapter16Condition;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Condition的await和signal
 * Created by LinGer on 2019/6/24
 */
public class ConditionTest extends Thread{

    /**
     * 获取非公平锁
     */
    private static Lock lock = new ReentrantLock();

    private static Condition condition = lock.newCondition();

    public ConditionTest(String name){
        super(name);
    }

    @Override
    public void run() {
        lock.lock();
        try{
            System.out.println(this.getName() + " wakeup others");
            condition.signal();
        }finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        ConditionTest ta = new ConditionTest("ta");
        lock.lock();
        try{
            System.out.println(Thread.currentThread().getName() + " start ta");
            ta.start();

            System.out.println(Thread.currentThread().getName() + " await");
            //等待
            condition.await();

            System.out.println(Thread.currentThread().getName() + " continue");

        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
}
